package com.binguo.thirdPay.aiBao;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
@Service
public class SendRequest {
 
    
    /**
     * 		根据商户编号获取Store-Secret的值
     * @param storeId	商户编号
     * @return			Store-Secret的值
     */
    public String getAiBaoStoreSecret(String storeId){
    	String storeIdMd5 = storeId+DigestUtils.md5Hex(storeId).toLowerCase();
    	
    	Base64 base64 = new Base64();
    	try {
    		return base64.encodeToString(storeIdMd5.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			System.out.println("商户编号生成Store-Secret异常");
		}
    	
    	return "";
    }
    
    
    
    /**
     * 		根据请求参数和Store-Secret生成StoreSign的值
     * @param params		请求参数
     * @param storeSecret	Store-Secret的值
     * @return		StoreSign的值
     */
    public String getAiBaoStoreSign(TreeMap<String,Object> params, String storeSecret) {
    	StringBuilder storeSign = new StringBuilder();
    	for (Map.Entry<String,Object> param : params.entrySet()) {
    		storeSign.append("&");
    		storeSign.append(param.getKey());
    		storeSign.append("=");
    		storeSign.append(param.getValue());
		}
    	storeSign.append("&key=");
    	storeSign.append(storeSecret);
    	String storeSignData = storeSign.toString().substring(1);
    	return DigestUtils.md5Hex(storeSignData).toUpperCase();
    }
    
    
    
    
    /**
     * 		拼接请求参数
     * @param params	请求参数集合
     * @return			拼接好的请求参数
     */
    public String getAiBaoParam(TreeMap<String,Object> params) {
    	StringBuilder storeSign = new StringBuilder();
    	for (Map.Entry<String,Object> param : params.entrySet()) {
    		storeSign.append("&");
    		storeSign.append(param.getKey());
    		storeSign.append("=");
    		storeSign.append(param.getValue());
		}
    	return storeSign.toString();
    }
    
    
    
    public String sendPost(String url, String storeId, String aiBaoStoreSign, String param) {
		String result = "";
		PrintWriter out = null;
		BufferedReader in = null;
		try {
			URL postUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection)postUrl.openConnection();
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			connection.setDoInput(true);
            connection.setRequestProperty("Store-Id", storeId);
            connection.setRequestProperty("Store-Sign", aiBaoStoreSign);
			
			out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()));
			out.write(param);
			out.flush();
			
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			line = null;
		} catch (MalformedURLException e) {
			System.out.println("SendRequest类中sendPost方法，创建URL对象异常");
		} catch (IOException e) {
			System.out.println("SendRequest类中sendPost方法，创建URL对象连接异常");
		} finally {
			try {
				if (out != null) { out.close();}
				if (in != null) { in.close();}
			} catch (IOException ex) {
				System.out.println("SendRequest类中sendPost方法，关闭IO异常");
			}
		}
		return result;
	}
    
    
    
    /**
     * 		unicode编码转中文
     * @param ascii		要转换的字符串
     * @return			中文字符串
     */
	public String ascii2native(String ascii) {
        List<String> ascii_s = new ArrayList<String>();
        String zhengz= "\\\\u[0-9,a-f,A-F]{4}";
        Pattern p = Pattern.compile(zhengz);
        Matcher m=p.matcher(ascii);
        
        while (m.find()){
            ascii_s.add(m.group());
        }

        for (int i = 0, j = 2; i < ascii_s.size(); i++) {
            String code = ascii_s.get(i).substring(j, j + 4);
            char ch = (char) Integer.parseInt(code, 16);
            ascii = ascii.replace(ascii_s.get(i),String.valueOf(ch));
        }
        return ascii;
	}
}